package com.mlan.userap.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ChatDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "chat.db";
    private static final int DATABASE_VERSION = 1;

    public ChatDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        if (!isTableExists(db, "messages")) {
            String createTable = "CREATE TABLE messages (" +
                    "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                    "msg_id TEXT NOT NULL UNIQUE," +
                    "group_id TEXT NOT NULL," +
                    "uid_from INTEGER NOT NULL," +
                    "msg_type INTEGER NOT NULL," +
                    "msg_content TEXT," +
                    "file_info TEXT," +
                    "msg_ticks INTEGER NOT NULL)";
            db.execSQL(createTable);
            db.execSQL("CREATE INDEX idx_ticks ON messages(msg_ticks)");
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 如果版本升级，可以在这里处理表结构变更
        // 当前逻辑：仅当表不存在时创建，不删除已有表
        if (!isTableExists(db, "messages")) {
            onCreate(db);
        }
        // 如果需要升级表结构（例如添加新字段），可以在这里添加 ALTER TABLE 语句
        // 示例：if (oldVersion < 2) { db.execSQL("ALTER TABLE messages ADD COLUMN new_field TEXT"); }
    }

    // 检查表是否存在
    private boolean isTableExists(SQLiteDatabase db, String tableName) {
        Cursor cursor = db.rawQuery(
                "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
                new String[]{tableName}
        );
        boolean exists = cursor.getCount() > 0;
        cursor.close();
        return exists;
    }
}